package com.zemo.base.api.controller.rest;

import com.zemo.base.api.controller.BaseController;
import com.zemo.base.common.util.StringUtils;
import com.zemo.base.common.util.WeiXinAuthUtil;
import com.zemo.base.domain.entity.sys.UserEntity;
import com.zemo.base.domain.enums.AccountSourceEnum;
import com.zemo.base.service.sys.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import java.io.IOException;
import java.util.Map;

/**
 * @ClassName: LoginRestController
 * @author: SuperZemo
 * @email: zemochen@gmail.com
 * @Date 06/04/2018 20:47
 * @Description 登陆授权
 */
@Controller
@RequestMapping("/api/login")
@Api(value = "登陆",description = "用户登陆授权相关接口")
public class LoginRestController extends BaseController {

    @Autowired
    private UserService userService;

    @ApiOperation(value = "微信登陆", notes = "微信登陆授权", httpMethod = "POST")
    @RequestMapping(value = "/weixin/login", method = RequestMethod.POST)
    public ModelAndView loginGet(@RequestParam(required = false) String code, @RequestParam(required = false) String state) throws IOException {

        Map<String, Object> map = WeiXinAuthUtil.getUserAccessToken(code, 0);

        String openId = (String) map.get("openid");
        String accessToken = (String) map.get("access_token");

        // 获取openid后验证登录
        if (StringUtils.isNotBlank(openId)) {
            UserEntity user = userService.getUserByToken( openId);
            if (user == null) {
                Map<String, Object> userInfo = WeiXinAuthUtil.getUserInfo(openId, accessToken);

                user = new UserEntity();
                //FIXME 有可能昵称重复
                user.setNickName((String) userInfo.get("nickname"));
                user.setPlainPwd(openId);
                user.setRegisterFrom(AccountSourceEnum.ACCOUNT_WEICHAT.getKey());
                user.setGender((Integer) userInfo.get("sex") == 1 ? 0 : 1);
                // 保存头像
                user.setAvatorUrl((String) userInfo.get("headimgurl"));
                userService.save(user);


            }
            /*if (!SecurityUtils.getSubject().isAuthenticated()) {
                WeixinToken weixinToken = new WeixinToken(openId);
                try {
                    SecurityUtils.getSubject().login(weixinToken);
                } catch (AuthenticationException ae) {
                    ae.printStackTrace();
                }
            }*/
            String redirectUrl = "";
            if (StringUtils.isNotBlank(state))
                redirectUrl = state;
            else
                redirectUrl = "/share/app/views/index/index.html";
            redirectUrl += "?openId=" + openId;
            return new ModelAndView(new RedirectView(redirectUrl, true));
        }

        // 未获取openid或未绑定
        return new ModelAndView(new RedirectView("/share/app/views/web/web.html", true));
    }

}
